package com.zwb.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zwb.boot.dto.SetmealDto;
import com.zwb.boot.entity.Setmeal;
import com.zwb.boot.entity.SetmealDish;
import com.zwb.boot.mapper.SetmealMapper;
import com.zwb.boot.service.SetmealDishService;
import com.zwb.boot.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 头发又黑又长
 * @Date 2022/7/22 15:26
 * @email zwb15083976291@163.com
 */
@Slf4j
@Service
@Transactional
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;


    /**
     * 根据 category id 查询 count
     *
     * @param id
     * @return
     */
    @Override
    public Long countByCategoryId(Long id) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getCategoryId, id);
        return this.count(queryWrapper);
    }

    /**
     * 保存套餐和 套餐-菜品
     *
     * @param setmealDto
     */
    @Override
    public void saveWithSetmealDish(SetmealDto setmealDto) {
        this.save(setmealDto);
        Long id = setmealDto.getId();
        List<SetmealDish> collect = setmealDto.getSetmealDishes().stream().map(item -> {
            // 设置套餐id
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(collect);


    }

    /**
     * 根据id 删除套餐
     *
     * @param ids
     */
    @Override
    public void deleteWithSetmealDish(List<Long> ids) {
        // 删除套餐
        this.removeBatchByIds(ids);

        LambdaQueryWrapper<SetmealDish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.in(SetmealDish::getSetmealId, ids);
        // 删除 套餐-菜品管理表
        setmealDishService.remove(dishLambdaQueryWrapper);
    }

    /**
     * 修改套餐信息 和 套餐-菜品表
     *
     * @param setmealDto
     */
    @Override
    public void updateWithSetmealDish(SetmealDto setmealDto) {
        this.updateById(setmealDto);

        // 删除原来的套餐-菜品表
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, setmealDto.getId());
        setmealDishService.remove(queryWrapper);

        // 添加菜品信息
        List<SetmealDish> collect = setmealDto.getSetmealDishes().stream().map(item -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(collect);

    }
}
